import { Action, createReducer, on } from '@ngrx/store';
import { AuthPayload, AuthState } from './auth.models';
import { AuthUser } from '@shared/models/user.models';
import {
  actionAuthAuthenticated,
  actionAuthLoadUser,
  actionAuthUnauthenticated,
  actionAuthUpdateAuthUser
} from './auth.actions';

// 默认用户
const defaultUser: AuthUser = {
  id: 'default',
  username: 'default',
  email: 'default@example.com',
  firstName: 'Default',
  lastName: 'User'
};

// 空的认证状态
const emptyUserAuthState: AuthPayload = {
  authUser: defaultUser
};

// 初始状态
export const initialState: AuthState = {
  isAuthenticated: false,
  isUserLoaded: false,
  ...emptyUserAuthState
};

// 创建 reducer
const reducer = createReducer(
  initialState,
  
  // 认证通过
  on(actionAuthAuthenticated, (state, { payload }) => ({
    ...state,
    isAuthenticated: true,
    ...payload
  })),
  
  // 未认证
  on(actionAuthUnauthenticated, state => ({
    ...state,
    isAuthenticated: false,
    ...emptyUserAuthState
  })),
  
  // 加载用户状态
  on(actionAuthLoadUser, (state, { isUserLoaded }) => ({
    ...state,
    isUserLoaded: isUserLoaded,
    isAuthenticated: isUserLoaded ? state.isAuthenticated : false,
    ...(isUserLoaded ? {} : emptyUserAuthState)
  })),
  
  // 更新认证用户
  on(actionAuthUpdateAuthUser, (state, { payload }) => ({
    ...state,
    ...payload
  }))
);

// 导出 reducer 函数
export function authReducer(state: AuthState | undefined, action: Action): AuthState {
  return reducer(state, action);
}
